import BasePanel from "../BasePanel";
import PackItem from "./PackItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class PackPanel extends BasePanel {
    private itemParent:cc.Node;
    

    onLoad(){
        this.close;        
        this.itemParent = this.node.getChildByName("scrollview").getChildByName("view").getChildByName("content");                              
        cc.log(this.itemParent);
        QM.game.on("packItem",this.updateUI,this);
    }

    start(){
        this.node.active = false;
    }

    firstCall(){    
        if(!this.isFirst) return;        
        this.isFirst = false;
        //初始化背包
        var packItems = QM.game.getPack();                
        for(let itemId in packItems){
            var com = this.itemParent.getChildByName("packItem").getComponent(PackItem);
            com.itemCount = packItems[itemId];
            com.itemId = Number(itemId);                
        }                        
    }

    /** 更新或者新加入一个物品 */
    updateUI(event:QM.QEvent){
        
        var data = event.data;
        if(this.isFirst){
            this.firstCall();
            return ;
        }

        //添加一个物品,或者修改一个物品的数量
        //1先查找当前物品是否存在                
        var packItem = this.itemParent.getChildByName(data.id.toString());        
        if(!packItem){
            //新增一个物品
            var com = this.itemParent.getChildByName("packItem").getComponent(PackItem);
            com.itemCount = data.count;
            com.itemId = data.id;
        }else{
            //修改物品数量
            var com = packItem.getComponent(PackItem);
            com.itemCount = data.count;
        }
    }

    /** 注销事件 */
    onDestroy(){
        QM.game.off("packItem");
    }

}
